/*
 * @Author: yangni 920556271@qq.com
 * @Date: 2023-12-25 17:18:47
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-04-09 10:07:24
 * @FilePath: /yt-devops/lib/pages/devices/device_tab/device_detail/battery_cell_tree/battery_cell_tree_controller.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import 'package:get/get.dart';
import 'package:yt_devops/components/yt_expandable_tree/model/tree_mode.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/services/device/device_sevices.dart';

import 'battery_cell_tree_model.dart';

class BatteryCellTreeController extends GetxController {
  DeviceServices services = Get.find();

  List<BatteryCellTreeModel> cells = [];

  List<String> get batteryCellNames =>
      cells.map((e) => e.deviceName ?? '').toList();

  BatteryCellTreeModel? selectedValue;

  List<TreeNode> treeNode = [];

  /// 锁， 用于选下级设备时节流
  bool isLocked = false;

  String deviceName = '电池';
  late int deviceId = 10736;

  @override
  void onInit() {
    var arg = Get.arguments;
    if (arg != null) {
      deviceId = arg['deviceId'];
      deviceName = arg['deviceName'];

      selectedValue = arg['model'];
    }
    super.onInit();

    getBatteryCell();
  }

  @override
  void onReady() {}

  @override
  void onClose() {}

  Future getBatteryCell() => Configs.httpClient.requestWithLoading(() async {
        var data = await services.getBatteryDevices({'deviceId': deviceId});
        cells =
            List.of(data).map((e) => BatteryCellTreeModel.fromMap(e)).toList();

        treeNode = [
          TreeNode('',
              title: deviceName,
              checkable: false,
              subNodes: TreeNode.listFrom<BatteryCellTreeModel>(
                  source: cells,
                  title: (int index, BatteryCellTreeModel item) =>
                      item.deviceName ?? '',
                  value: (int index, BatteryCellTreeModel item) =>
                      item.deviceId))
        ];
        update();
      });

  selected(TreeNode newVal) {
    if (isLocked) return;
    isLocked = true;
    BatteryCellTreeModel? cell =
        cells.firstWhereOrNull((element) => element.deviceId == newVal.value);
    if (cell != null) {
      Future.delayed(const Duration(milliseconds: 500), () {
        Get.back<BatteryCellTreeModel>(result: cell);
        isLocked = false;
      });
    }
  }
}
